//
//  GHQauthController.m
//  12-guhu_weibo
//
//  Created by GHapple on 15-2-3.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "GHQauthController.h"

@interface GHQauthController ()<UIWebViewDelegate>

@end

@implementation GHQauthController

#define  GHAccessTokenUrl @"https://api.weibo.com/oauth2/access_token"
#define GHAuthorizeUrl @"https://api.weibo.com/oauth2/authorize"
#define GHclientId @"3528856179"

#define GHClientSecret @"c284b931bf49b19bd00fe257ae665989"
#define GHRedirectUri  @"http://baidu.com"


- (void)loadView{

    self.view = [[UIWebView alloc]init];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    [self loadQauthpage];
}

/**
 *  加载登录界面
 */
- (void)loadQauthpage{
    
    //拼接请求路径
    NSString *urlstring = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",GHAuthorizeUrl,GHclientId,GHRedirectUri];
    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLRequest *request = [NSURLRequest  requestWithURL:url];
    // 加载网页
    
    UIWebView *webView = (UIWebView *)self.view;
    [webView loadRequest:request];
    webView.delegate = self;
    
    


}
- (void)close{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 代理方法

// 当web发送请求的时候就会调用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    // 判断即将要请求的url中是否含有code = ,如果包含说明已经拿到了已经授权的requestToken ,就不需要请求下一个页面了
//     将url转为字符串
    NSString *urlString = request.URL.absoluteString;
    //  查找是否含有code=
    NSRange range = [urlString rangeOfString:@"code="];
    //看是否含有code = 如果有则返回索引和长度,没有则索引为NOTFound
    if (range.location != NSNotFound) {
        // 说明已经取得了授权的token  截取 token   即为code = 后面的
        NSUInteger  startIndex  = range.location + range.length;
        NSString *code = [urlString substringFromIndex:startIndex];
        [self accessTokenWithCode:code];
        return  NO;
    }
    
    
    return YES;
}



//  根据已经授权的RequestToken换取AccessToken
- (void)accessTokenWithCode:(NSString *)code{
// 通过AFN来进行网络请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  // 使用管理对象来放松请求
    NSMutableDictionary *parameters = [NSMutableDictionary  dictionary];
    // 通过字典封装请求的参数
    parameters[@"client_id"] = GHclientId;
    parameters[@"client_secret"] = GHClientSecret;
    parameters[@"grant_type"] =  @"authorization_code";
    parameters[@"code"] = code;
    parameters[@"redirect_uri"] = GHRedirectUri;
    
    // 添加返回数据支持的类型
    
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObject:@"text/plain"];
    [manager POST:GHAccessTokenUrl parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        GHLog(@"成功 = %@",responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        GHLog(@"失败 -----%@",error);
    }];
}



//加载网页调用
- (void)webViewDidStartLoad:(UIWebView *)webView{

    [SVProgressHUD showWithStatus:@"正在拼命加载中...." maskType:SVProgressHUDMaskTypeBlack];
}
// 加载完毕了调用
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];

}
// 加载出错的时候调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [SVProgressHUD dismiss];

}


@end
